package com.exm.collectcodenew.juc.threadPool;

import java.util.concurrent.*;

/**
 * 代码（7）的get会一直阻塞不返回。如果把拒绝策略修改为 DiscardOldestPolicy，也会存在有一个任务的get方法一直阻塞，只是现在是任务 two 被阻塞。但是如果把拒绝策略设置为默认的 AbortPolicy则会正常返回，
 */
public class FutureTest {
    //(1)线程池单个线程，线程池队列元素个数为1
    private final static ThreadPoolExecutor executorService = new ThreadPoolExecutor(1,1,1L,
            TimeUnit.MINUTES,new ArrayBlockingQueue<Runnable>(1),
            new ThreadPoolExecutor.DiscardPolicy()
//            new ThreadPoolExecutor.AbortPolicy()
//            new MyRejectedExecutionHandler()
    );
    public static class MyRejectedExecutionHandler implements RejectedExecutionHandler{
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if(!e.isShutdown()){
                if(null != r && r instanceof FutureTask){
                    ((FutureTask<?>) r).cancel(true);
                }
            }
        }
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //（2）添加任务one
       Future futureOne = executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("start runable one");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //（3）添加任务two
        Future futureTwo =  executorService.submit(()-> System.out.println("start runable two"));
        //（4）添加任务three
        Future futureThree =null;
        try {
            futureThree = executorService.submit(() -> System.out.println("start runable three"));
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
        }
        System.out.println("task one "+futureOne.get());//(5)等待任务one执行完毕
        System.out.println("task two "+futureTwo.get());//(6)等待任务two执行完毕
        System.out.println("task three "+(futureThree==null?null:futureThree.get()));//(7)等待任务three执行完毕
        executorService.shutdown();//(8)关闭线程池，阻塞直到所有任务执行完毕
    }
}
